<template>
  <view class="container">
    <uni-nav-bar :title="'工作记录详情'" left-icon="arrowleft" @clickLeft="goBack"></uni-nav-bar>
    
    <scroll-view scroll-y class="detail-container">
      <view class="detail-card">
        <view class="detail-header">
          <text class="container-number">{{ detailData.container_number }}</text>
          <text class="container-type">{{ detailData.container_type }}</text>
        </view>
        
        <view class="detail-row">
          <text class="label">装货日期:</text>
          <text class="value">{{ detailData.loading_date }}</text>
        </view>
        
        <view class="detail-row">
          <text class="label">车辆信息:</text>
          <text class="value">{{ detailData.car || '未指定' }}</text>
        </view>
        
        <view class="detail-row">
          <text class="label">提箱地点:</text>
          <text class="value">{{ detailData.pickup_location || '未填写' }}</text>
        </view>
        
        <view class="detail-row">
          <text class="label">还箱地点:</text>
          <text class="value">{{ detailData.dropoff_location || '未填写' }}</text>
        </view>
        
        <view class="detail-row">
          <text class="label">门点位置:</text>
          <text class="value">{{ detailData.loading_location || '未填写' }}</text>
        </view>
        
        <view class="detail-row">
          <text class="label">提/装/卸/进:</text>
          <view class="checkbox-group">
            <label class="checkbox-label">
              <checkbox value="提箱" :checked="isOperationChecked('提箱')" @change="handleOperationChange('提箱')" />
              <text>提箱</text>
            </label>
            <label class="checkbox-label">
              <checkbox value="装货" :checked="isOperationChecked('装货')" @change="handleOperationChange('装货')" />
              <text>装货</text>
            </label>
			<label class="checkbox-label">
			  <checkbox value="卸货" :checked="isOperationChecked('卸货')" @change="handleOperationChange('卸货')" />
			  <text>卸货</text>
			</label>
            <label class="checkbox-label">
              <checkbox value="进港" :checked="isOperationChecked('进港')" @change="handleOperationChange('进港')" />
              <text>还箱</text>
            </label>
          </view>
        </view>
        
        <view class="detail-row">
          <text class="label">GPS坐标:</text>
          <text class="value">{{ detailData.gps_latitude && detailData.gps_longitude ? `${detailData.gps_latitude}, ${detailData.gps_longitude}` : '未填写' }}</text>
        </view>
        
        <view class="detail-row">
          <text class="label">提还箱费用:</text>
          <text class="value fee">¥{{ detailData.pickup_return_fee || 0 }}</text>
        </view>
        
        <view class="detail-row">
          <text class="label">备注:</text>
          <text class="value">{{ detailData.remarks || '无' }}</text>
        </view>
        
        <view class="detail-row" v-if="detailData.photo_path">
          <text class="label">照片:</text>
          <image class="photo" :src="getFullImageUrl(detailData.photo_path)" mode="aspectFit" @click="previewImage"></image>
        </view>
        
        <view class="detail-row created-at">
          <text class="label">创建时间:</text>
          <text class="value">{{ detailData.created_at }}</text>
        </view>
      </view>
      
      <view class="action-buttons">
        <button class="edit-button" @click="goToEdit">编辑</button>
        <button class="delete-button" @click="confirmDelete">删除</button>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import api from '@/store/work_api.js';
import uniNavBar from '@dcloudio/uni-ui/lib/uni-nav-bar/uni-nav-bar.vue';
export default {
	components: {
	    uniNavBar
	  },
  data() {
    return {
      detailData: {},
      id: '',
	  operations: ['提箱', '装货', '卸货', '进港'] // 定义所有可能的操作类型
    }
  },
  onLoad(options) {
    this.id = options.id;
    this.loadDetail();
  },
  methods: {
	getFullImageUrl(relativePath) {
	  if (!relativePath) return '';
	  
	  // 替换为您的服务器基础URL
	  const baseUrl = 'http://192.168.1.42:8000/'; 
	  
	  // 处理可能已经包含基础URL的情况
	  if (relativePath.startsWith('http')) {
	    return relativePath;
	  }
	  
	  // 处理Windows路径的反斜杠
	  const normalizedPath = relativePath.replace(/\\/g, '/');
	  
	  // 确保不以斜杠开头
	  const cleanPath = normalizedPath.startsWith('/') 
	    ? normalizedPath.substring(1) 
	    : normalizedPath;
	  
	  return baseUrl + cleanPath;
	},
	// 检查某个操作是否被选中
	isOperationChecked(operation) {
	    if (!this.detailData.order_type || !this.detailData.order_type.length) {
	        return false
	    }
	    return this.detailData.order_type.includes(operation)
	},   
	// 处理操作类型变化
	handleOperationChange(operation) {
	    if (!this.detailData.order_type) {
	        this.detailData.order_type = []
	    }
	      
	    const index = this.detailData.order_type.indexOf(operation)
	    if (index === -1) {
	        // 添加操作
	        this.detailData.order_type.push(operation)
	    } else {
	        // 移除操作
	        this.detailData.order_type.splice(index, 1)
	    }
	      
	    // 如果需要实时保存到服务器，可以在这里调用API
	    this.updateOperations()
	},
	// 格式化order_type数据（用于从服务器获取数据后处理）
	formatDoorLocation(data) {
			if (data.order_type) {
				// 如果order_type是字符串，转换为数组
				if (typeof data.order_type === 'string') {
					data.order_type = data.order_type.split(',').filter(item => item.trim())
				}
				// 如果order_type是null或undefined，设置为空数组
				if (!data.order_type) {
					data.order_type = []
				}
			} else {
				data.order_type = []
			}
			return data
	    },
	  
	
	
    goBack() {
      uni.navigateBack();
    },
    
    async loadDetail() {
		uni.showLoading({
			title: '加载中'
		});
      
		try {
			const response = await api.getWorkRecordDetail(this.id);
		      
		    // 检查响应结构
		        if (!response) {
		          throw new Error('服务器返回空响应');
		        }
		    
		        // 处理uni.request的响应格式
		        if (response.statusCode) {
		          // HTTP状态码检查
		          if (response.statusCode !== 200) {
		            throw new Error(`HTTP错误: ${response.statusCode}`);
		          }
		          
		          // 检查响应数据
		          if (!response.data) {
		            throw new Error('响应数据为空');
		          }
		          
		          // 处理业务数据
		          if (response.data.status === 'success') {
		            this.detailData = this.formatResponseData(response.data.data);
		          } else {
		            throw new Error(response.data.message || '业务逻辑错误');
		          }
		        } 
		        // 处理直接返回业务数据的情况
		        else if (response.status === 'success') {
		          this.detailData = this.formatResponseData(response.data);
		        } 
		        // 其他情况
		        else {
		          throw new Error('未知的响应格式');
		        }
		} catch (err) {
			console.error('加载详情错误:', err);
			uni.showToast({
				title: err.message || '加载详情失败',
				icon: 'none',
				duration: 2000
			});
			setTimeout(() => {
				this.goBack();
			}, 1500);
		} finally {
			uni.hideLoading();
		}
    },
	// 格式化响应数据
	formatResponseData(data) {
	  // 处理order_type
	  if (data.order_type) {
	    if (typeof data.order_type === 'string') {
	      // 将字符串"提箱,装货,进港"转换为数组["提箱", "装货", "进港"]
	      data.order_type = data.order_type.split(',')
	        .map(item => item.trim())
	        .filter(item => item);
	    } else if (!Array.isArray(data.order_type)) {
	      data.order_type = [];
	    }
	  } else {
	    data.order_type = [];
	  }
	  
	  return data;
	},
	// 如果需要保存到服务器
	async updateOperations() {
	    try {
	        const res = await api.updateWorkRecord({
				id: this.id,
				order_type: this.detailData.order_type.join(',')
	        })
	        // 处理响应...
	    } catch (err) {
	        console.error('更新操作类型失败:', err)
	    }
	},
    
    goToEdit() {
      uni.navigateTo({
        url: `/pages/work/add?id=${this.id}`
      });
    },
    
    previewImage() {
      if (!this.detailData.photo_path) return;
      
      const fullUrl = this.getFullImageUrl(this.detailData.photo_path);
      uni.previewImage({
        urls: [fullUrl]
      });
    },
    
    confirmDelete() {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这条工作记录吗？',
        success: (res) => {
          if (res.confirm) {
            this.deleteRecord();
          }
        }
      });
    },
    
    async deleteRecord() {
      uni.showLoading({
        title: '删除中...'
      });
      
      try {
        const res = await api.deleteWorkRecord(this.id);
        const [error, data] = res;
        
        if (error || data.status !== 'success') {
          throw new Error('删除失败');
        }
        
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        });
        
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } catch (err) {
        uni.showToast({
          title: '删除失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    }
  }
}
</script>

<style>
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.detail-container {
  flex: 1;
  padding: 20rpx;
}

.detail-card {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 30rpx;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.container-number {
  font-size: 36rpx;
  font-weight: bold;
}

.container-type {
  background-color: #f0f0f0;
  padding: 5rpx 15rpx;
  border-radius: 30rpx;
  font-size: 26rpx;
}

.detail-row {
  display: flex;
  margin-bottom: 20rpx;
}

.detail-row .label {
  width: 160rpx;
  color: #666;
  font-size: 28rpx;
}

.detail-row .value {
  flex: 1;
  font-size: 28rpx;
}

.detail-row .fee {
  color: #e74c3c;
  font-weight: bold;
}

.photo {
  width: 200rpx;
  height: 200rpx;
  margin-top: 10rpx;
}

.created-at {
  margin-top: 30rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #eee;
  color: #999;
  font-size: 26rpx;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
}

.edit-button, .delete-button {
  flex: 1;
  margin: 0 10rpx;
}

.edit-button {
  background-color: #3498db;
  color: white;
}

.delete-button {
  background-color: #e74c3c;
  color: white;
}

.checkbox-group {
  display: flex;
  flex: 1;
  justify-content: space-between;
  align-items: center;
}

.checkbox-label {
  display: flex;
  align-items: center;
  margin-right: 20rpx;
}

.checkbox-label text {
  margin-left: 10rpx;
  font-size: 28rpx;
}
</style>